package com.multi.mybatisplus.seata.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.multi.mybatisplus.seata.mapper.order.OrderMapper;
import com.multi.mybatisplus.seata.mapper.store.GoodsMapper;
import com.multi.mybatisplus.seata.pojo.BizConstant;
import com.multi.mybatisplus.seata.pojo.Order;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.seata.core.context.RootContext;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * @author Administrator
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/business")
public class BusinessController {
    private final OrderMapper orderMapper;
    private final GoodsMapper goodsMapper;

    /**
     * 添加订单
     */
    @GetMapping("/add/{goodsId}/{count}")
    @GlobalTransactional(timeoutMills = 300000, rollbackFor = Exception.class)
    public String addOrder(@PathVariable(value = "goodsId") Long goodsId,
                           @PathVariable(value = "count") Integer count,
                           @RequestParam(value = "isFail", required = false, defaultValue = "0") Integer isFail) {
        Order order = new Order();
        order.setOrderId(IdUtil.getSnowflakeNextId());
        order.setGoodsId(goodsId);
        order.setCount(count);
        int orderResult = orderMapper.insertOneOrder(order);
        log.info("新增订单：{}，结果：{}", JSON.toJSONString(order), orderResult);

        int goodsResult = goodsMapper.updateGoodsStock(goodsId, -count);
        log.info("修改库存结果：{}", goodsResult);

        if (isFail == 1) {
            int divide = 0;
            int resul = 100 / divide;
        }

        if (goodsResult > 0) {
            return BizConstant.SUCCESS;
        } else {
            return BizConstant.FAIL;
        }
    }

    /**
     * 添加订单
     */
    @GetMapping("/addRest/{goodsId}/{count}")
    @GlobalTransactional(timeoutMills = 300000, rollbackFor = Exception.class)
    public String addOrderRest(@PathVariable(value = "goodsId") Long goodsId,
                               @PathVariable(value = "count") Integer count,
                               @RequestParam(value = "isFail", required = false, defaultValue = "0") Integer isFail) {
        String xid = RootContext.getXID();
        log.info("xid before send:{}", xid);
        if (StringUtils.isEmpty(xid)) {
            return BizConstant.FAIL;
        }
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add(RootContext.KEY_XID, xid);

        String addOrderUrl = "http://127.0.0.1:8888/order/add/" + IdUtil.getSnowflakeNextId() + "/" + goodsId + "/" + count;
        String orderResult = restTemplate.postForObject(addOrderUrl, new HttpEntity<String>(headers), String.class);
        log.info("新增订单：{}，结果：{}", addOrderUrl, orderResult);
        if (!BizConstant.SUCCESS.equals(orderResult)) {
            throw new RuntimeException();
        }

        String updateStockUrl = "http://127.0.0.1:8888/goods/stock/" + goodsId + "/" + (-count);
        String goodsResult = restTemplate.postForObject(updateStockUrl, new HttpEntity<String>(headers), String.class);
        log.info("修改库存：{}，结果：{}", updateStockUrl, goodsResult);
        if (!BizConstant.SUCCESS.equals(goodsResult)) {
            throw new RuntimeException();
        }

        if (isFail == 1) {
            int divide = 0;
            int resul = 100 / divide;
        }
        return BizConstant.SUCCESS;
    }
}

